// Copyright 2019 Hackware SpA <human@hackware.cl>
// This file is part of "Hackware Userland" and licensed under the terms
// of the GNU Affero General Public License version 3, or (at your option)
// a later version. You should have received a copy of this license along
// with the software. If not, see <https://www.gnu.org/licenses/>.

export default class Auth {
  constructor($fetcher) {
    this.user = JSON.parse(sessionStorage.getItem('user'));
    this.$fetcher = $fetcher;
  }

  setUser(user) {
    this.user = user;
    sessionStorage.setItem('user', JSON.stringify(this.user));
  }

  get uid() {
    return this.user.uid;
  }

  logout() {
    this.user = null;
    sessionStorage.removeItem('user');
  }

  isLoggedIn() {
    if (this.user) {
      return true;
    }

    return false;
  }

  fetchUser(authToken = null, processResponse = true) {
    const headers = authToken ? { Authorization: `Bearer ${authToken}` } : {};

    return this.$fetcher.haweseGet('/auth/whoami', {}, headers, processResponse);
  }
}
